package com.yanq.liancar.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.MyShopAdapter;
import com.yanq.liancar.adapter.MyfindAdapter;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.MyFindBean;
import com.yanq.liancar.bean.MyShopBean;
import com.yanq.liancar.bean.QueryUserBaseMessageBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.UserFindAttentionBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyFollowActivity extends BaseToolbarActivity {

    @BindView(R.id.ll_find)
    LinearLayout llFind;
    @BindView(R.id.ll_shop)
    LinearLayout llShop;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_find)
    TextView tvFind;
    @BindView(R.id.view_find)
    View viewFind;
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.view_shop)
    View viewShop;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;
    @BindView(R.id.ck_all)
    CheckBox mCheckBox;
    @BindView(R.id.ll_noMessage)
    LinearLayout ll_noMessage;
    private int type = 1;    //1:发现  2：店铺
    private MyfindAdapter myfindAdapter;
    private MyShopAdapter myShopAdapter;
    private int page;
    private boolean isClear=true;
    private boolean isDelete = true;
    private List<UserFindAttentionBean.DataBean> myFindBeanList = new ArrayList<>();
    private List<MyShopBean.DataBean> myShopBeanList = new ArrayList<>();
    private List<String> mShopList = new ArrayList<>();
    private List<String> mFindList = new ArrayList<>();
    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    private double Latitude,Longitude;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myfollow);
        Utils.setStatusBar(this, true, false);
        ButterKnife.bind(this);
        mTvTitle.setText("我的关注");
        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setTextColor(getResources().getColor(R.color.main_color));
        mTvRight.setText("编辑");
        getLocation();
        mTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isDelete) {
                    if (type == 1) {
                        if (!myFindBeanList.isEmpty() || myFindBeanList.size() != 0) {
                            mTvRight.setText("完成");
                            mTvRight.setTextColor(getResources().getColor(R.color.red));
                            isDelete = false;
                            rlContent.setVisibility(View.VISIBLE);
                            for (int i = 0; i < myFindBeanList.size(); i++) {
                                myFindBeanList.get(i).setGone(true);
                            }
                            myfindAdapter.notifyDataSetChanged();
                        }else {
                            RxToast.normal("当前没有更多内容");
                        }
                    } else {
                        if (!myShopBeanList.isEmpty() || myShopBeanList.size() != 0) {
                            mTvRight.setText("完成");
                            mTvRight.setTextColor(getResources().getColor(R.color.red));
                            isDelete = false;
                            rlContent.setVisibility(View.VISIBLE);
                            for (int i = 0; i < myShopBeanList.size(); i++) {
                                myShopBeanList.get(i).setGone(true);
                            }
                            myShopAdapter.notifyDataSetChanged();
                        }else {
                            RxToast.normal("当前没有更多内容");
                        }
                    }
                    mCheckBox.setChecked(false);

                } else {
                    mTvRight.setText("编辑");
                    mTvRight.setTextColor(getResources().getColor(R.color.main_color));
                    isDelete = true;
                    rlContent.setVisibility(View.GONE);

                    if (type == 1) {
                        if (!myFindBeanList.isEmpty() || myFindBeanList.size() != 0) {
                            for (int i = 0; i < myFindBeanList.size(); i++) {
                                myFindBeanList.get(i).setGone(false);
                                myFindBeanList.get(i).setStatus(false);
                            }
                            myfindAdapter.notifyDataSetChanged();
                            mCheckBox.setChecked(false);
                        }
                    } else {
                        if (!myShopBeanList.isEmpty() || myShopBeanList.size() != 0) {
                            for (int i = 0; i < myShopBeanList.size(); i++) {
                                myShopBeanList.get(i).setGone(false);
                                myShopBeanList.get(i).setStatus(false);
                            }
                            myShopAdapter.notifyDataSetChanged();
                            mCheckBox.setChecked(false);
                        }
                    }
                }
            }
        });

        tvFind.setTextColor(getResources().getColor(R.color.background_content));
        viewFind.setBackgroundColor(getResources().getColor(R.color.main_color));
        tvShop.setTextColor(getResources().getColor(R.color.gray));
        viewShop.setBackgroundColor(getResources().getColor(R.color.main_bg));
        initRecyclerview();
        initListener();
        initOkGoFind();

    }


    @OnClick({R.id.ll_find, R.id.ll_shop, R.id.ck_all, R.id.tv_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_find:
                recyclerview.setAdapter(myfindAdapter);
                tvFind.setTextColor(getResources().getColor(R.color.background_content));
                viewFind.setBackgroundColor(getResources().getColor(R.color.main_color));
                tvShop.setTextColor(getResources().getColor(R.color.gray));
                viewShop.setBackgroundColor(getResources().getColor(R.color.main_bg));
                type = 1;
                initOkGoFind();
                mTvRight.setText("编辑");
                isDelete = true;
                rlContent.setVisibility(View.GONE);
                mTvRight.setTextColor(getResources().getColor(R.color.main_color));
                break;
            case R.id.ll_shop:
                recyclerview.setAdapter(myShopAdapter);
                tvFind.setTextColor(getResources().getColor(R.color.gray));
                viewFind.setBackgroundColor(getResources().getColor(R.color.main_bg));
                tvShop.setTextColor(getResources().getColor(R.color.background_content));
                viewShop.setBackgroundColor(getResources().getColor(R.color.main_color));
                type = 2;
                initOkGoShop();
                mTvRight.setText("编辑");
                isDelete = true;
                rlContent.setVisibility(View.GONE);
                mTvRight.setTextColor(getResources().getColor(R.color.main_color));
                break;
            case R.id.ck_all:
                if (type == 1) {
                    if (myFindBeanList.isEmpty()||myFindBeanList.size()!=0){
                        if (mCheckBox.isChecked()){
                            for (int i = 0; i <myFindBeanList.size() ; i++) {
                                myFindBeanList.get(i).setStatus(true);
                            }
                            myfindAdapter.notifyDataSetChanged();
                        }else {
                            for (int i = 0; i <myFindBeanList.size() ; i++) {
                                myFindBeanList.get(i).setStatus(false);
                            }
                            myfindAdapter.notifyDataSetChanged();
                        }

                        summary(1);
                    }
                } else {
                    if (!myShopBeanList.isEmpty() || myShopBeanList.size() != 0) {
                        if (mCheckBox.isChecked()) {
                            for (int i = 0; i < myShopBeanList.size(); i++) {
                                myShopBeanList.get(i).setStatus(true);
                            }
                            myShopAdapter.notifyDataSetChanged();
                        } else {
                            for (int i = 0; i < myShopBeanList.size(); i++) {
                                myShopBeanList.get(i).setStatus(false);
                            }
                            myShopAdapter.notifyDataSetChanged();
                        }

                        summary(2);
                    }
                }
                break;
            case R.id.tv_delete:
                LogUtils.e("sdadada", mShopList.size() + "");
                LogUtils.e("sdadada", mFindList.size() + "");
                if (type==1){
                    OkGoDeleteNews();
                }else {
                    OkGoDeleteShop();
                }
                break;
        }
    }

    private void initRecyclerview() {
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));

        myfindAdapter = new MyfindAdapter(R.layout.item_myfind, myFindBeanList);
        recyclerview.setAdapter(myfindAdapter);
        myfindAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle=new Bundle();
                bundle.putInt("newsId",myFindBeanList.get(position).getNewsid());
                RxActivityTool.skipActivity(MyFollowActivity.this, NewsDetailsActivity.class,bundle);
            }
        });
        myfindAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.img_checked:
                        myFindBeanList.get(position).setStatus(!myFindBeanList.get(position).isStatus());
                        myfindAdapter.notifyDataSetChanged();
                        if (isFindAllCheck()) {
                            mCheckBox.setChecked(true);
                        } else {
                            mCheckBox.setChecked(false);
                        }
                        summary(1);
                        break;
                }
            }
        });

        myShopAdapter = new MyShopAdapter(R.layout.item_myfuwu, myShopBeanList);
        myShopAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle=new Bundle();
                bundle.putInt("shopId",myShopBeanList.get(position).getId());
                RxActivityTool.skipActivity(mContext, ShopDetailsActivity.class,bundle);
            }
        });
        myShopAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.img_checked:
                        myShopBeanList.get(position).setStatus(!myShopBeanList.get(position).isStatus());
                        myShopAdapter.notifyDataSetChanged();
                        if (isShopAllCheck()) {
                            mCheckBox.setChecked(true);
                        } else {
                            mCheckBox.setChecked(false);
                        }
                        summary(2);
                        break;
                }
            }
        });


    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                isClear = true;

//                if (type == 1) {
//                    initOkGoFind();
//                } else {
//                    initOkGoShop();
//                }
                refreshlayout.finishRefresh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                isClear = false;
//                if (type == 1) {
//                    initOkGoFind();
//                } else {
//                    initOkGoShop();
//                }
                refreshLayout.finishLoadMore();
            }

        });
    }

    //发现
    private void initOkGoFind() {
        OkGo.<String>post(Config.s + "llc/api/selectUserFindAttention")
                .tag(this)
                .params("token", UserBean.getcToken(mContext))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        UserFindAttentionBean bean = gson.fromJson(response.body(), UserFindAttentionBean.class);
                        if (bean.isIsSuccess()) {
                            if (bean.getCode()==200){
                                myFindBeanList.clear();
                                myFindBeanList.addAll(bean.getData());
                                myfindAdapter.setNewData(myFindBeanList);
                                ll_noMessage.setVisibility(View.GONE);
                            }else {
                                myFindBeanList.clear();
                                myfindAdapter.notifyDataSetChanged();
                                ll_noMessage.setVisibility(View.VISIBLE);
                            }
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }

                    }
                });
    }

    //店铺
    private void initOkGoShop() {
        OkGo.<String>post(Config.s + "llc/attenShopController/getAttenShop")
                .tag(this)
                .params("token", UserBean.getcToken(mContext))
                .params("lat", Latitude)
                .params("lon", Longitude)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        MyShopBean bean = gson.fromJson(response.body(), MyShopBean.class);
                        if (bean.isIsSuccess()) {
                            if (bean.getCode()==200){

                            }
                            if (isClear) {
                                myShopBeanList.clear();
                            }
                            myShopBeanList.addAll(bean.getData());
                            myShopAdapter.setNewData(myShopBeanList);
                            if (myShopBeanList.size()<1){
                                ll_noMessage.setVisibility(View.VISIBLE);
                            }else {
                                ll_noMessage.setVisibility(View.GONE);
                            }
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }

                    }
                });
    }

    //删除关注店铺
    private void OkGoDeleteShop() {
        OkGo.<String>post(Config.s + "llc/attenShopController/deleteAttenShop")
                .tag(this)
                .params("token", UserBean.getcToken(mContext))
                .addUrlParams("ids", mShopList)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()) {
                            mTvRight.setText("编辑");
                            mTvRight.setTextColor(getResources().getColor(R.color.main_color));
                            isDelete = true;
                            rlContent.setVisibility(View.GONE);
                            initOkGoShop();
                            RxToast.success(bean.getOutputMessage());
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }

                    }
                });
    }

    //删除关注新闻
    private void OkGoDeleteNews() {
        OkGo.<String>post(Config.s + "llc/api/delectUserFindAttention")
                .tag(this)
                .params("token", UserBean.getcToken(mContext))
                .addUrlParams("newsid", mFindList)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()) {
                            RxToast.success(bean.getOutputMessage());
                            initOkGoFind();
                            mTvRight.setText("编辑");
                            mTvRight.setTextColor(getResources().getColor(R.color.main_color));
                            isDelete = true;
                            rlContent.setVisibility(View.GONE);
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }

                    }
                });
    }

    public void summary(int type) {
        if (type == 1) {
            for (int i = 0; i < myFindBeanList.size(); i++) {
                if (myFindBeanList.get(i).isStatus()) {
                    mFindList.add(myFindBeanList.get(i).getNewsid()+"");
                } else {
                    if (mFindList.contains(myFindBeanList.get(i).getNewsid())) {
                        mFindList.remove(myFindBeanList.get(i).getNewsid());
                    }
                }
            }
        } else {
            for (int i = 0; i < myShopBeanList.size(); i++) {
                if (myShopBeanList.get(i).isStatus()) {
                    mShopList.add(myShopBeanList.get(i).getId() + "");
                } else {
                    if (mShopList.contains(myShopBeanList.get(i).getId())) {
                        mShopList.remove(myShopBeanList.get(i).getId()+"");
                    }
                }
            }
        }
    }

    private boolean isShopAllCheck() {
        for (int i = 0; i < myShopBeanList.size(); i++) {
            if (!myShopBeanList.get(i).isStatus()) {
                return false;
            }
        }
        return true;
    }

    private boolean isFindAllCheck() {
        for (int i = 0; i < myFindBeanList.size(); i++) {
            if (!myFindBeanList.get(i).isStatus()) {
                return false;
            }
        }
        return true;
    }

    private void getLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        //        /**
        //         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
        //         */
        //        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        //        if(null != mLocationClient){
        //            mLocationClient.setLocationOption(mLocationOption);
        //            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        //            mLocationClient.stopLocation();
        //            mLocationClient.startLocation();
        //        }

        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果
        mLocationOption.setOnceLocation(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        Latitude=aMapLocation.getLatitude();//获取纬度
                        Longitude=aMapLocation.getLongitude();//获取经度
                        LogUtils.e("经纬度====",Latitude+"======="+Longitude);
                        if (type == 1) {
                            initOkGoFind();
                        } else {
                            initOkGoShop();
                        }
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }
    }
}
